package com.cc.data_explore.gui.importfile;

import com.cc.data_explore.gui.helper.StageHelper;
import com.cc.data_explore.logic.excel.FileLogic;
import com.cc.data_explore.logic.mybatis.DbHelper;
import com.cc.data_explore.logic.mybatis.mapper.sub.FileDataMapper;
import com.cc.data_explore.logic.mybatis.mapper.sub.FileInfoMapper;
import com.cc.data_explore.logic.mybatis.model.FileInfo;
import de.saxsys.mvvmfx.ViewModel;
import javafx.beans.property.*;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.dromara.hutool.core.data.id.IdUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileTypeUtil;
import org.dromara.hutool.core.text.CharPool;
import org.dromara.hutool.core.text.StrUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ImportDialogView
 *
 * @author aa
 * @version 1.0
 * @since 2025/3/27
 */
public class ImportFileDialogViewModel implements ViewModel {
    private final StringProperty filePath = new SimpleStringProperty();
    private final ListProperty<Delimiter> csvDelimiterProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
    private final ObjectProperty<Delimiter> selectedDelimiterProperty = new SimpleObjectProperty<>();
    private final ListProperty<String> sheetList = new SimpleListProperty<>(FXCollections.observableArrayList());
    private final BooleanProperty visibleProperty = new SimpleBooleanProperty(false);
    private final BooleanProperty saveBtnProperty = new SimpleBooleanProperty(true);
    private final BooleanProperty readBtnProperty = new SimpleBooleanProperty(false);

    public void initialize() {
        System.out.println("ImportFileDialogViewModel初始化完成");
        ObservableList<Delimiter> delimiters = FXCollections.observableArrayList();
        delimiters.add(new Delimiter("逗号", CharPool.COMMA));
        delimiters.add(new Delimiter("Tab", CharPool.TAB));
        csvDelimiterProperty.setAll(delimiters);
    }

    public ReadOnlyListProperty<String> sheetListProperty() {
        return sheetList;
    }

    public StringProperty filePathProperty() {
        return filePath;
    }

    public ReadOnlyListProperty<Delimiter> csvDelimiterProperty() {
        return csvDelimiterProperty;
    }

    public ObjectProperty<Delimiter> selectedDelimiterProperty() {
        return selectedDelimiterProperty;
    }

    public BooleanProperty visibleProperty() {
        return visibleProperty;
    }

    public ObservableValue<Boolean> saveBtnProperty() {
        return saveBtnProperty;
    }

    public ObservableValue<Boolean> readBtnProperty() {
        return readBtnProperty;
    }

    public void readFile(String text) {
        if (StrUtil.isEmpty(text)) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setContentText("文件路径不能为空");
            alert.initOwner(StageHelper.getStage(StageHelper.MAIN_STAGE));
            alert.showAndWait();
            return;
        }
        sheetList.clear();
        Map<String, Integer> sheetMap;
        if (visibleProperty.get()) {
            Delimiter delimiter = selectedDelimiterProperty.get();
            if (delimiter == null) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setContentText("请选择分隔符");
                alert.initOwner(StageHelper.getStage(StageHelper.MAIN_STAGE));
                alert.showAndWait();
                return;
            }
            sheetMap = FileLogic.readSheetMap(text, delimiter.getValue());
        } else {
            sheetMap = FileLogic.readSheetMap(text);
        }
        sheetMap.forEach((sheetName, count) -> sheetList.add(StrUtil.format("{}({})", sheetName, count)));
        saveBtnProperty.set(false);
        readBtnProperty.set(true);
    }

    public void browse() {
        // 创建一个 FileChooser 实例
        FileChooser fileChooser = new FileChooser();
        // 设置文件选择器的标题
        fileChooser.setTitle("选择文件");
        // 设置文件选择器的初始目录（可选）
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        // 设置文件过滤器，这里只允许选择 Excel 文件
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Files", "*.xlsx", "*.xls", "*.csv"));
        // 显示文件选择器对话框，并获取用户选择的文件
        File selectedFile = fileChooser.showOpenDialog(new Stage());
        if (selectedFile != null) {
            // 如果用户选择了文件，将文件路径设置到 filePath 文本框中
            filePath.setValue(selectedFile.getAbsolutePath());
            String fileType = FileTypeUtil.getType(selectedFile);
            if (StrUtil.containsIgnoreCase(fileType, "csv")) {
                visibleProperty.setValue(true);
            }
        }
    }

    public String getText(Delimiter delimiter) {
        return delimiter.getText();
    }

    public void saveData() {
        List<FileInfo> fileInfoList = new ArrayList<>();
        long fileId = IdUtil.getSnowflakeNextId();
        String filePathValue = filePath.getValue();
        String fileName = FileNameUtil.getName(filePathValue);
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileName(fileName);
        fileInfo.setFilePath(filePathValue);
        fileInfo.setId(fileId);
        fileInfo.setPid(0L);
        fileInfo.setFileType(visibleProperty.get() ? 0 : 1);
        fileInfo.setNum(1);
        fileInfoList.add(fileInfo);
        Map<String, Long> sheetIdMap = new HashMap<>();
        for (String st : sheetList) {
            long sheetId = IdUtil.getSnowflakeNextId();
            FileInfo sheet = new FileInfo();
            sheet.setId(sheetId);
            sheet.setPid(fileId);
            sheet.setFileName(st);
            sheet.setFilePath(filePathValue);
            sheet.setFileType(2);
            sheet.setNum(1);
            fileInfoList.add(sheet);
            String[] split = st.split("\\(");
            sheetIdMap.put(split[0], sheetId);
        }
        SqlSessionFactory sqlSessionFactory = DbHelper.getInstance().getSqlSessionFactory();
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            FileInfoMapper mapper = sqlSession.getMapper(FileInfoMapper.class);
            FileDataMapper dataMapper = sqlSession.getMapper(FileDataMapper.class);
            mapper.insert(fileInfoList);
            FileLogic.readData(filePathValue, fileId, sheetIdMap, dataMapper::insert);
        }
    }

}
